<template>
  <div>
    <div class="header">
      <h1>Vue3 + DeepSeek 智能对话</h1>
      <p>基于DeepSeek API的聊天应用示例</p>
    </div>

    <div class="chat-container">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="[
          'message',
          message.role === 'user' ? 'user-message' : 'ai-message',
        ]"
      >
        <div class="message-content">
          {{ message.content }}
        </div>
      </div>

      <div v-if="isLoading" class="loading">
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
      </div>

      <div v-if="error" class="error">
        {{ error }}
      </div>
    </div>

    <div class="input-area">
      <input
        v-model="userInput"
        @keypress="handleKeyPress"
        placeholder="输入你的消息..."
        :disabled="isLoading"
      />
      <button @click="sendMessage" :disabled="isLoading">
        {{ isLoading ? "发送中..." : "发送" }}
      </button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from "vue";
import {
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";
import axios from "axios";
// const { ref, onMounted } = Vue
const messages = ref([]);
const userInput = ref("");
const isLoading = ref(false);
const error = ref(null);

// 模拟API密钥（实际应用中应从安全的后端获取）
const API_KEY = "sk-29eb3573a91a44589a9f121e6ad5e717";
const API_URL = "https://api.deepseek.com/v1/chat/completions";

// 发送消息到DeepSeek API
const sendMessage = async () => {
  if (!userInput.value.trim() || isLoading.value) return;

  const userMessage = userInput.value.trim();
  userInput.value = "";
  messages.value.push({ role: "user", content: userMessage });
  isLoading.value = true;
  error.value = null;

  try {
    const response = await axios.post(
      API_URL,
      {
        model: "deepseek-chat",
        messages: [
          { role: "system", content: "你是一个有帮助的AI助手。" },
          ...messages.value,
        ],
        temperature: 0.7,
        max_tokens: 2048,
      },
      {
        headers: {
          Authorization: `Bearer ${API_KEY}`,
          "Content-Type": "application/json",
        },
      }
    );

    const aiMessage = response.data.choices[0].message.content;
    messages.value.push({ role: "assistant", content: aiMessage });
  } catch (err) {
    console.error("API请求错误:", err);
    error.value =
      err.response?.data?.error?.message || "请求失败，请检查API密钥和网络连接";
  } finally {
    isLoading.value = false;
  }
};

// 处理回车键发送
const handleKeyPress = (event) => {
  if (event.key === "Enter" && !event.shiftKey) {
    event.preventDefault();
    sendMessage();
  }
};

// 滚动到最新消息
const scrollToBottom = () => {
  const container = document.querySelector(".chat-container");
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
};

// 当消息更新时滚动到底部
onMounted(() => {
  scrollToBottom();
});

// 监听消息变化
watch(messages, scrollToBottom, { deep: true });
</script>
<style scoped lang="scss">
.header {
  background: linear-gradient(135deg, #6e8efb, #a777e3);
  color: white;
  padding: 20px;
  text-align: center;
  h1{
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;

  }
}
.chat-container {
  height: 400px;
  overflow-y: auto;
  padding: 20px;
  background: #fafafa;
}
.message {
  margin-bottom: 16px;
  display: flex;
}
.user-message {
  justify-content: flex-end;
}
.ai-message {
  justify-content: flex-start;
}
.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  line-height: 1.4;
}
.user-message .message-content {
  background: #6e8efb;
  color: white;
  border-bottom-right-radius: 4px;
}
.ai-message .message-content {
  background: #e8ebf0;
  color: #333;
  border-bottom-left-radius: 4px;
}
.input-area {
  display: flex;
  padding: 16px;
  border-top: 1px solid #eaeaea;
  background: white;
}
input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #ddd;
  border-radius: 24px;
  outline: none;
  font-size: 16px;
}
input:focus {
  border-color: #6e8efb;
}
button {
  margin-left: 10px;
  padding: 0 24px;
  background: #6e8efb;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-weight: bold;
  transition: background 0.2s;
}
button:hover {
  background: #5d7df0;
}
button:disabled {
  background: #ccc;
  cursor: not-allowed;
}
.loading {
  display: flex;
  justify-content: center;
  padding: 10px;
}
.dot {
  width: 8px;
  height: 8px;
  margin: 0 4px;
  background: #a777e3;
  border-radius: 50%;
  animation: bounce 1.5s infinite;
}
.dot:nth-child(2) {
  animation-delay: 0.2s;
}
.dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes bounce {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}
.error {
  color: #e74c3c;
  text-align: center;
  padding: 10px;
  background: #ffecec;
  margin: 10px;
  border-radius: 6px;
}
</style>
<style></style>
